package cn.acewill.yxd.yunxundian.componet;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkInfo;
import android.os.Build;
import android.util.Log;
import android.widget.Toast;

/**
 * Created by Carson_Ho on 16/10/31.
 */
public class NetWorkStateReceiver extends BroadcastReceiver {

    public static int whetherConnectNetWork = -1;
    public static int netWorkType = 0;

    @Override
    public void onReceive(Context context, Intent intent) {
        ConnectivityManager mConnectivityManager = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        //API 23
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            //获取所有网络连接的信息
            Network[] networks = mConnectivityManager.getAllNetworks();
            //用于存放网络连接信息
            StringBuilder sb = new StringBuilder();
            //通过循环将网络信息逐个取出来
            for (int i = 0; i < networks.length; i++) {
                //获取ConnectivityManager对象对应的NetworkInfo对象
                NetworkInfo networkInfo = mConnectivityManager.getNetworkInfo(networks[i]);
                sb.append(networkInfo.getType() + "|" + networkInfo.isConnected());
                if (networkInfo != null && networkInfo.isConnected()) {
                    whetherConnectNetWork = 1;
                    int type = networkInfo.getType();
                    if (type == ConnectivityManager.TYPE_WIFI) {
                        netWorkType = 1;
                    } else if (type == ConnectivityManager.TYPE_MOBILE) {
                        netWorkType = 2;
                    }
                }
            }

        }else {

            NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
            if (mNetworkInfo != null && mNetworkInfo.isConnected()) {
                whetherConnectNetWork = 1;
                int type = mNetworkInfo.getType();
                if (type == ConnectivityManager.TYPE_WIFI) {
                    netWorkType = 1;
                } else if (type == ConnectivityManager.TYPE_MOBILE) {
                    netWorkType = 2;
                }
//            Toast.makeText(context,"网络已连接",Toast.LENGTH_SHORT).show();
            } else {
                whetherConnectNetWork = 0;
//            Toast.makeText(context,"无网络连接",Toast.LENGTH_SHORT).show();

            }
        }

    }
}
